// Requester.js
var config = require('../config/config');
var util = require('./util.js');
var User = require('./User.js');

let waitting = [];

function requests(obj) {
    // 是否请求，要看当前队列里面的数目是否超出数量
    if (waitting.length <= 5) {
        waitting.unshift(obj);
    }
    let objs = waitting.pop();
    this.request(objs);
}

function getCommonParam() {
    return util.getSessionId();
}

/**
 * 请求网络
 * @param obj
 */
function request(obj) {
    return new Promise((resolve, reject) => {
        let sessionId = getCommonParam();
        obj.data.cSessionId = sessionId || '';
        obj.data.userSource = config.userSource;
        obj.url = obj.host ? obj.host : ''
            + config.domain.requestDomain + obj.url;
        obj.success = function (res) {
            if (res.data.code === 1002) {
                // cSessionId已经过期
                console.log("cSessionId已经过期", "重新联网登录...");
                User.userLogin().then(() => {
                    console.log("重新登录成功", "再次请求接口...");
                    obj.data.cSessionId = getCommonParam() || '';
                    wx.request(obj);
                });
            } else {
                console.log("请求接口成功!");
                resolve(res.data);
            }
        };
        obj.fail = function (res) {
            reject(res);
        };
        wx.request(obj);
    }).catch(err => {
        console.log(err);
        throw Error(err);
    })
}

/**上传图片 */
function uploadFile(obj) {
    let sessionId = getCommonParam();
    obj.formData.cSessionId = sessionId || '';
    obj.url = obj.host ? obj.host : ''
        + config.domain.requestDomain + obj.url;
    let objSuccess = obj.success;
    obj.success = function (res) {
        if (res.data.code === 1002) {
            // cSessionId已经过期
            User.userLogin(() => {
                obj.formData.cSessionId = getCommonParam() || '';
                wx.uploadFile(obj);
            });
        } else {
            typeof objSuccess === 'function' && objSuccess(res);
        }
    };
    wx.uploadFile(obj);
}

module.exports = {
    request: request,
    uploadFile: uploadFile,
    domain: config.domain,
    service: config.service
};
